package com.freeseed.model.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.freeseed.model.entity.User;
import com.freeseed.model.entity.UserDtl;
import com.freeseed.model.mapper.UserDtlMapper;
import com.freeseed.model.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.security.PublicKey;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Allwayz
 * @since 2020-03-20
 */
@Slf4j
@RestController
@RequestMapping("users")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserDtlMapper userDtlMapper;

    @GetMapping
    public List<User> getUserList(){
        List<User> userList = userMapper.selectList(new QueryWrapper<>());
        return userList;
    }

    @GetMapping("{Id}")
    public User getUserBuId(@PathVariable int Id){
        User user = userMapper.selectById(Id);
        return user;
    }

    @PostMapping
    public  User addUser(User user){
        userMapper.insert(user);
        //用户细节信息不另外创建，在创建用户的时候直接创建用户细节，并且用selectCount方法得到FK：UserId
        int i = userMapper.selectCount(new QueryWrapper<>());
        UserDtl userDtl = UserDtl.builder()
                .userId(i)
                .build();
        userDtlMapper.insert(userDtl);
        return user;
    }

    @PutMapping
    public User updateUser(User user){
        userMapper.update(user,new UpdateWrapper<User>().eq("user_id",user.getUserId()));
        return user;
    }

    @DeleteMapping("{Id}")
    public void deleteUserById(@PathVariable int Id){
        userMapper.deleteById(Id);
        userDtlMapper.deleteById(Id);
    }
}
